package com.mjlf.mqserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mjlf.mqserver.entity.Message;
import com.mjlf.mqserver.inter.MessageFactory;
import com.mjlf.mqserver.server.MessageServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName MessageController
 * @Author mjlft
 * @Date 2020/2/19 12:57
 * @Version 1.0
 * @Description TODO
 */
@RestController
public class MessageController  {

    @Autowired
    private MessageServer messageServer;

    @PostMapping("/insertMessage")
    public JSONObject insertMessage(@RequestBody JSONObject params) throws Exception {
        messageServer.insertMessage(params.getString("topicName"), params.getString("message"));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 200);
        return jsonObject;
    }

    @PostMapping("/getMessage")
    public String getMessage(@RequestBody JSONObject params) throws Exception {
        return messageServer.getMessage(params.getString("topicName"), params.getString("groupName"));
    }

    @PostMapping("/synMessage")
    public JSONObject synMessage(@RequestBody JSONObject param){
        String topicName = param.getString("topicName");
        int index = param.getInteger("index");

        JSONObject result = new JSONObject();
        List<Message> messages = MessageFactory.message.get(topicName);
        if(messages == null){
            messages = new ArrayList<>();
            MessageFactory.message.put(topicName, messages);
        }

        JSONArray jsonArray = new JSONArray();
        if(messages.size() > index){
            for(int i = index; i < messages.size(); i++){
                Message message = messages.get(i);
                JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(message));
                jsonArray.add(jsonObject);
            }
        }

        result.put("code", 200);
        result.put("data", jsonArray);
        return result;
    }

    @GetMapping("/synConsumerIndex")
    public JSONObject synMessage(){
        JSONObject jsonObject = new JSONObject();
        JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(MessageFactory.customerIndex));
        jsonObject.put("code", 200);
        jsonObject.put("data", data);
        return jsonObject;
    }
}
